package ioc

import (
	"forum/internal/adapter/driving/dao"
	"forum/pkg/gormx"
	"github.com/prometheus/client_golang/prometheus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormProme "gorm.io/plugin/prometheus"
)

func InitMysqlDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:13316)/forum"))
	if err != nil {
		panic(err)
	}
	//prometheus
	err = db.Use(gormProme.New(gormProme.Config{
		DBName:          "forum",
		RefreshInterval: 15,
		MetricsCollector: []gormProme.MetricsCollector{
			&gormProme.MySQL{
				VariableNames: []string{"thread_running"},
			},
		},
	}))
	cb := gormx.NewCallbacks(prometheus.SummaryOpts{
		Namespace: "geekmokou",
		Subsystem: "forum",
		Name:      "gorm_db",
		Help:      "统计 GORM 的数据库查询",
		ConstLabels: map[string]string{
			"instance_id": "my_instance",
		},
		Objectives: map[float64]float64{
			0.5:   0.01,
			0.75:  0.01,
			0.9:   0.01,
			0.99:  0.001,
			0.999: 0.0001,
		},
	})
	err = db.Use(cb)
	if err != nil {
		panic(err)
	}
	CreateTable(db)
	return db
}

func CreateTable(db *gorm.DB) {
	err := db.AutoMigrate(
		&dao.User{},
		&dao.Article{},
		&dao.PublishArticle{},
	)
	if err != nil {
		panic(err)
	}
}
